goog.provide('td.Bullet');

goog.require('Stefan.Circle');

td.Bullet = T.lang.createClass(function(config){
	Stefan.Circle.call(this);
	this.init(config);
}, {
	superClass: Stefan.Circle
}).extend({
	init: function (config) {
		var cfg = config || {};
		this.speed = cfg.speed;
		this.damage = cfg.damage;
		this.target = cfg.target;
		this.index = 0;
		this.pX = cfg.pX;
		this.pY = cfg.pY;
	
		this.weapon = cfg.weapon || null;
		this.map = this.weapon.map;
		var color = cfg.color || '#000000';
		this.setSize(0.2 * td.GRIDSIZE, 0.2 * td.GRIDSIZE);
		this.setAnchor(.5, .5)
		this.setFill(color);
	
		this.map.bulletArr.push(this);
		this.index = this.map.bulletArr.length - 1;
		this.map.appendChild(this);
		this.setPosition(this.pX, this.pY);
	
		this.caculate();
	},
	
	caculate: function () {
		var distanceX = this.target.pX - this.pX;
		var distanceY = this.target.pY - this.pY;
		//计算斜边距离
		var distanceXY = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
		var	speed = this.speed * td.GRIDSIZE;
		//X方向速度分量
		this.speedX = distanceX * speed / distanceXY;
		//Y方向速度分量
		this.speedY = distanceY * speed / distanceXY;
	},
	
	
	checkHit: function () {
		var hitArmy;
		var armyArr = this.map.armyArr;
		for(var i = 0, maxi = armyArr.length; i < maxi; i++){
			var army = armyArr[i];
			if(army && Math.pow(army.pX - this.pX, 2) + Math.pow(army.pY - this.pY, 2) <= Math.pow(army.cfg.size, 2)){
				hitArmy = army;
				break;
			}
		}
		if (hitArmy) {
			hitArmy.beHit(this.weapon, this.damage);
			this.destroy();
			return true;
		}
		return false;
	},
		
	destroy: function(){
		var blen = this.map.bulletArr.length;
		if(this.index !== blen - 1){
			for(var i = this.index + 1; i < blen; i++){
				this.map.bulletArr[i].index--;
			}
		}
		this.map.bulletArr.splice(this.index, 1);
		this.map.removeChild(this);
		delete this;
	},
	
	step: function () {
		if (this.checkHit()) return;
		this.pX += this.speedX;
		this.pY += this.speedY;
		if(this.pX <= 0 || this.pY <=0 || this.pX >= this.map.width || this.pY >= this.map.width) this.destroy();
		else this.setPosition(this.pX, this.pY);
	}
});
